package com.yzcrm.erp.admin.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.entity.AdminMenu;
import com.yzcrm.erp.admin.entity.AdminRole;
import com.yzcrm.erp.admin.entity.AdminRoleMenu;
import com.yzcrm.utils.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AdminMessageService {

    /**
     * 查询用户个人消息
     * @param userId
     * @param page
     * @param limit
     * @return
     */
    public R queryMessage(Long userId, Integer page, Integer limit) {

        page = (page-1)*limit;

        Kv kv = new Kv();
        kv.put("userId", userId);
        kv.put("page", page);
        kv.put("limit", limit);

        SqlPara sqlPara = Db.getSqlPara("admin.message.queryMessage", kv);
        List<Record> recordPage = Db.find(sqlPara);
        recordPage.forEach(record -> {

            Integer isAnonymous = record.getInt("is_anonymous");
            if(ObjectUtil.isNotNull(isAnonymous) && isAnonymous == 1) {
                record.set("create_user_name", "***");
                record.set("create_user", "");
            }

        });

        SqlPara countSql = Db.getSqlPara("admin.message.queryMessageCount", kv);
        Integer count = Db.queryInt(countSql.getSql(), countSql.getPara());


        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("list", recordPage);
        resultJsonObject.put("totalRow", count);
        return R.ok().put("data", resultJsonObject);
    }

    /**
     * 个人未查看消息总数
     * @return
     */
    public R unreadMessageCount(Long userId){

        Kv kv = new Kv();
        kv.put("userId", userId);

        SqlPara countSql = Db.getSqlPara("admin.message.queryMessageUnreadCount", kv);
        Integer count = Db.queryInt(countSql.getSql(), countSql.getPara());

        JSONObject resultJsonObject = new JSONObject();
        resultJsonObject.put("count", count);
        return R.ok().put("data", resultJsonObject);
    }

    /**
     * 消息阅读
     * @return
     */
    public R readMessage(Integer messageId){

        Db.update(Db.getSql("admin.message.readMessage"), messageId);

        return R.ok();
    }

}
